package com.star.spring.sharding.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.star.spring.sharding.entity.Address;
import com.star.spring.sharding.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    /**
     * 创建地址
     */
    @PostMapping("/create")
    public String createAddress(@RequestParam Long userId,
                               @RequestParam String addressName,
                               @RequestParam String detailAddress) {
        Address address = new Address(userId, addressName, detailAddress);
        addressService.save(address);
        return "地址创建成功，地址ID: " + address.getAddressId();
    }

    /**
     * 根据地址ID查询地址
     */
    @GetMapping("/{addressId}")
    public Address getAddressById(@PathVariable Long addressId) {
        return addressService.getById(addressId);
    }

    /**
     * 根据用户ID查询地址列表
     */
    @GetMapping("/user/{userId}")
    public List<Address> getAddressesByUserId(@PathVariable Long userId) {
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return addressService.list(queryWrapper);
    }

    /**
     * 更新地址
     */
    @PutMapping("/{addressId}")
    public String updateAddress(@PathVariable Long addressId,
                               @RequestParam String addressName,
                               @RequestParam String detailAddress) {
        Address address = addressService.getById(addressId);
        if (address != null) {
            address.setAddressName(addressName);
            address.setDetailAddress(detailAddress);
            addressService.updateById(address);
            return "地址更新成功";
        } else {
            return "地址不存在";
        }
    }

    /**
     * 删除地址
     */
    @DeleteMapping("/{addressId}")
    public String deleteAddress(@PathVariable Long addressId) {
        addressService.removeById(addressId);
        return "地址删除成功";
    }
}